package com.project.frba.bifront.client;

import java.util.Date;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.project.frba.bifront.client.rpc.UserServices;
import com.project.frba.bifront.client.rpc.UserServicesAsync;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class GwtFront implements EntryPoint {
	
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		String sessionId = Cookies.getCookie("sid");
		if(sessionId != null){
			checkWithServerIfSessionIdIsStillLegal(sessionId);
		} else {
			new LoginWindow(this);
		}	
	}

	private void checkWithServerIfSessionIdIsStillLegal(final String sessionId) {
		final GwtFront me = this;
		AsyncCallback<Boolean> acSessionValid = new AsyncCallback<Boolean>(){
			public void onFailure(Throwable caught) {
				Window.alert("Error: session could not be loaded.");
				
			}
			public void onSuccess(Boolean valid) {
				if(valid){
					if (sessionId.contains("A")) {
						afterLoguedIn(true);
					} else {
						afterLoguedIn(false);
						
					}
				} else {
					Cookies.removeCookie("sid");
					new LoginWindow(me);
				}
				
			}
		};
		UserServicesAsync userServices = (UserServicesAsync)GWT.create(UserServices.class);
		userServices.validateSessionId(sessionId, acSessionValid);
	}

	public void login(String sessionId){
	    final long DURATION = 1000 * 60 * 60 * 24 * 14; //duration remembering login. 2 weeks
	    Date expires = new Date(System.currentTimeMillis() + DURATION);
	    Cookies.setCookie("sid", sessionId, expires, null, "/", false);
	    if (sessionId.contains("A")) {
			afterLoguedIn(true);
		} else {
			afterLoguedIn(false);
			
		}
	}
	
	private void afterLoguedIn(Boolean isAdmin){
		RootPanel.get().add(new BiPanel(this, isAdmin));
	}
	
	public void logout(){
		new LoginWindow(this);
	}
}
